#include "playpcmthread.h"
#include <QDebug>
#include <SDL2/SDL.h>
#include <SDL2/SDL_audio.h>
#include <QFile>
#define SAMPLE_RATE 44100

#define SAMPLES 1024

#define FORMAT AUDIO_S16LSB

#define SIZE 16

#define CHANNELS 2

#define BYTES_PER_SAMPLE ((CHANNELS * SIZE) / 8)

#define BUFFER_SIZE (SAMPLES * BYTES_PER_SAMPLE)


int buffer_len = 0;
char *buffer_gloab;

void pull_audio_data(void *userdata, Uint8 * stream, int len) {

    //清空缓存的数据
    memset(stream,0,len);

    if(buffer_len <=0) {

        return;
    }

    len = (len > buffer_len)? buffer_len:len;

    SDL_MixAudio(stream,(Uint8 *)buffer_gloab,len,SDL_MIX_MAXVOLUME);

    buffer_len -= len;
    buffer_gloab += len;

}


PlayPCMThread::PlayPCMThread(QObject *parent) : QThread(parent){


    init();
}

PlayPCMThread::~PlayPCMThread()
{

    disconnect();

    requestInterruption();

    quit();
    wait();
    qDebug() << "PlayPCMThread destroy";

}

void PlayPCMThread::init()
{

    connect(this,&QThread::finished, this,&QThread::deleteLater);
}

void PlayPCMThread::run()
{

    if (SDL_Init(SDL_INIT_AUDIO)) {

        qDebug() << "init audio fail";
    }

    SDL_AudioSpec spec;

    // 采样率
    spec.freq = SAMPLE_RATE;
    // 声道数
    spec.channels = CHANNELS;
    // 采样格式(位深度)
    spec.format = FORMAT;
    // 音频缓冲区的样本数量
    spec.samples = SAMPLES;

    spec.callback = pull_audio_data;

    if (SDL_OpenAudio(&spec,nullptr)) {

        qDebug() << "open audio fail " << SDL_GetError();
        SDL_Quit();
        return;
    }

    const char* FILE_PATH = "/Users/tgy/Documents/ffmpeg/audio/in.pcm";
    QFile file(FILE_PATH);

    if (!file.open(QFile::ReadOnly)) {

        qDebug("QFile::ReadOnly");
        SDL_CloseAudio();
        SDL_Quit();
        return;
    }


    SDL_PauseAudio(0);

    char data[BUFFER_SIZE];

    while (!isInterruptionRequested()) {

        if (buffer_len > 0) {

            continue;
        }

        buffer_len = file.read(data,BUFFER_SIZE);

        // 数据读完了
        if (buffer_len <=0) {

            break;
        }

        buffer_gloab = data;
    }

    file.close();
    SDL_CloseAudio();
    SDL_Quit();
}


